package com.simple.crawler.aop;

import com.simple.crawler.core.CrawlerContext;
import com.simple.crawler.annotation.Aop;
import com.simple.crawler.utils.ReflectUtils;
import net.sf.cglib.proxy.Enhancer;

import java.util.Arrays;

public class AopHelper {

    private static AopHelper aopHelper;

    private AopHelper() {

    }

    public static AopHelper getAopHelper() {
        if (aopHelper == null) {
            aopHelper = new AopHelper();
        }
        return aopHelper;
    }

    public <T> T initObj(Class<T> c, Object... args) {
        Aop aop = ReflectUtils.getAnnotation(c, Aop.class);
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(c);
        /*enhancer.setCallbackFilter(method -> CrawlerContext.getObj(aop.filter()).dispatch(method));
        enhancer.setCallbacks(Arrays.asList(aop.callback()).stream().
                map(cName -> CrawlerContext.getObj(cName)).
                toArray(obj -> new Listener[aop.callback().length])
        );*/
        enhancer.setCallback(ReflectUtils.newInstance(aop.callback()));
        if (args == null || args.length == 0) {
            return (T) enhancer.create();
        }
        return (T) enhancer.create(Arrays.stream(args).map(arg -> arg.getClass()).toArray(arg -> new Class<?>[args.length]), args);
    }

}
